package cn.iocoder.mall.statistics.application.controller.pay;

import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.utils.common.api.vo.Result;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.util.MapSortUtil;
import cn.iocoder.common.utils.common.util.ObjectUtils;
import cn.iocoder.common.utils.common.util.TimeUtils;
import cn.iocoder.mall.order.api.OrderService;
import cn.iocoder.mall.order.api.bo.OrderBO;
import cn.iocoder.mall.order.api.bo.OrderPayAllChartBO;
import cn.iocoder.mall.order.api.vo.OrdersVO;
import cn.iocoder.mall.shop.api.ShopService;
import cn.iocoder.mall.shop.api.pojo.ShopDTO;
import io.prometheus.client.Collector;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.checkerframework.checker.units.qual.K;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: LL
 * @Date: 2019/12/13 10:45
 */
@RestController
@RequestMapping("/payChart")
@Slf4j
public class PayStatisticsController {
    @Reference(validation = "true",version = "${dubbo.consumer.OrderService.version}")
    OrderService orderService;
    @Reference(validation = "true", version = "${dubbo.consumer.ShopService.version}")
    ShopService shopService;

    /**
     * type 1 获取商户一天的营业额  3 ：获取商户一个月的营业额
     * @param ordersVO
     * @return
     */
    @GetMapping("/merchant/dayofmonth")
    public Result<?> getpayChart(OrdersVO ordersVO)  {
        List<ShopDTO> data = shopService.getListOfStores("7081ce121f69ab1d130747a39ddbaa0c").getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);
        CommonResult<List<OrderPayAllChartBO>>  orderChartBO= null;
        try {
            orderChartBO = orderService.getpayAllChart(ordersVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(orderChartBO);
    }

    /**
     * type 3 获取商户 各个商店本月的销售额 已排序 降序
     * @param ordersVO
     * @return
     */
    @GetMapping("/merchant/rightmonth")
    public Result<?> getRightMonth(OrdersVO ordersVO){
        List<ShopDTO> data = shopService.getListOfStores("7081ce121f69ab1d130747a39ddbaa0c").getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);
        CommonResult<List<OrderPayAllChartBO>>  orderChartBO= null;
        Map<String, List<OrderPayAllChartBO>> result=null;
            orderChartBO = orderService.getpayMonth(ordersVO);
            CommonResult<List<ShopDTO>> shopNames= shopService.getShopInfoById(shopIds);
        return Result.ok(orderChartBO.getData().stream().map(a->ObjectUtils.copyObject(a,OrderPayAllChartBO.class)
        .setShopName(shopNames.getData().stream()
        .filter(shopDTO -> shopDTO.getId().equals(a.getShopId()))
        .map(ShopDTO::getShopName)
        .findFirst().orElse(""))).collect(Collectors.toList())
                .stream().sorted(Comparator.comparing(OrderPayAllChartBO::getPresentPrice).reversed()).collect(Collectors.toList()));
    }

    /**
     * 获取商户一周 2 一月 3 一年 4 销售 柱状图使用
     * @param ordersVO
     * @return
     */
    @GetMapping("/merchant/monthofYear")
    public Result<?> getMonthofYear(OrdersVO ordersVO)  {
        List<ShopDTO> data = shopService.getListOfStores("7081ce121f69ab1d130747a39ddbaa0c").getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);
        Map<String, Integer> resultMap = null;
        Map<String, Integer> stringIntegerMap = null;
        try {
            resultMap = orderService.getpayMonthofYear(ordersVO);
           stringIntegerMap = MapSortUtil.sortByKeyAsc(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(stringIntegerMap);
    }

    /**
     * 5 折线图 获取商户 各个店铺一个月的销售额
     * @param ordersVO
     * @return
     */
    @GetMapping("/merchant/bottomMonth")
    public CommonResult getBottomMonth(OrdersVO ordersVO){
        List list ;
        List<String> shopIds ;
        Map<String,Integer> totalMap = new HashMap<>();
        SimpleDateFormat fmt = new SimpleDateFormat("dd");
        Map<String,Integer> map = new HashMap<>();
        Map<String,List> shopMap = new HashMap<>();
        Long monthStartTimes = TimeUtils.getMonthStartTime(System.currentTimeMillis(), "GMT+8:00");
        String s5 = TimeUtils.timestampToStr(monthStartTimes);
        Long monthEndTimes = TimeUtils.getMonthEndTime(System.currentTimeMillis(), "GMT+8:00");
        String s6 = TimeUtils.timestampToStr(monthEndTimes);
        ordersVO.setStartCreateTime(s5);
        ordersVO.setEndCreateTime(s6);

//        String userIdByToken = JwtUtil.getUserIdByToken();
        //获取商铺ID和商铺名称  5059093269671d8344e730e5a292daa7
        List<ShopDTO> data = shopService.getListOfStores("5059093269671d8344e730e5a292daa7").getData();
        if (data == null || data.size() == 0){
            return CommonResult.error("没有店铺信息");
        }
        shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);

        //获取当月每个店铺每天的营业额
        List<OrderBO> listCommonResult = orderService.getpayMonthForSalesVolume(ordersVO).getData();
        if(listCommonResult == null || listCommonResult.isEmpty()){
            return CommonResult.error("本月该店铺没有营业额");
        }
        for(int i = 0; i < data.size(); i++){
            list = new ArrayList();
            ShopDTO shopDTO = data.get(i);
            for(int j = 0; j < listCommonResult.size(); j++){
                OrderBO orderBO = listCommonResult.get(j);

                if(orderBO.getShopId().equals(shopDTO.getId())){
                    if (map.containsKey(fmt.format(orderBO.getClosingTime()))) {
                        int monthPrices = map.get(fmt.format(orderBO.getClosingTime())) + (orderBO.getPresentPrice() == null?0:orderBO.getPresentPrice());
                        map.put(fmt.format(orderBO.getClosingTime()), monthPrices);
                    } else {
                        map.put(fmt.format(orderBO.getClosingTime()),(orderBO.getPresentPrice() == null?0:orderBO.getPresentPrice()));
                    }
                    if (!list.contains(map)){
//                        Map<String, Integer> resultMap = MapSortUtil.sortByKeyAsc(map);
                        list.add(map);
                    }
                }
            }
            shopMap.put(shopDTO.getShopName(),list);
        }
        return CommonResult.success(shopMap);
    }

}
